package ar.com.hc.utils.hibernate.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import ar.com.hc.controller.HCController;

class HCHibernateInvocationHandler implements InvocationHandler {

	public static final String PERSISTENCE_UNIT = "HCPersistenceUnit";
	private EntityManagerFactory factory;
	private EntityManager em;

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		// inicia la transacción
		beginTransaction();
		// hace cosas
		HCController controller = (HCController) proxy;
		controller.setEm(em);
		Object result = method.invoke(controller, args);
		// finaliza la transacción
		endTransaction();
		return result;
	}

	private void endTransaction() {
		em.getTransaction().commit();
		em.close();
		factory.close();
	}

	private void beginTransaction() {
		this.factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
		this.em = factory.createEntityManager();
		em.getTransaction().begin();
	}
}
